package api;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 用户注册
 */

@WebServlet("/reg")
public class RegServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        int data = 0; //返回的结果标识，1表示注册成功
        String msg = "未知错误"; //错误的信息描述
        //1、从前端得到参数
        String username = req.getParameter("username");
        String nickname = req.getParameter("nickname");
        String password = req.getParameter("password");
        //非空效验
        if(!StrUtil.isBlank(username) &&
                !StrUtil.isBlank(nickname) &&
                !StrUtil.isBlank(password)){
            //2、将数据保存到数据库
            //得到连接
            Connection connection = DBUtils.getConnection();
            //因为username设置了唯一，所以要判断唯一
            String selSql = "select * from userinfo where username=?";
            PreparedStatement statement = connection.prepareStatement(selSql);
            statement.setString(1,username);
            ResultSet resultSet = statement.executeQuery();
            if(resultSet.next()){
                msg = "用户名已存在！";
            }
            else{
                String sql = "insert into userinfo(username,nickname,password) values(?,?,?)";
                statement =  connection.prepareStatement(sql);
                statement.setString(1,username);
                statement.setString(2,nickname);
                statement.setString(3, SecureUtil.md5(password));
                data = statement.executeUpdate();
            }

            //关闭资源
            DBUtils.close(resultSet,statement,connection);

        }else{
            msg = "非法参数";
        }

        //3、将数据库返回的结果响应给前端
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,data,msg)));
    }
}
